package com.lmonkey.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebFilter("/shangc/forgetcheck")
public class ForgetCheck implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest reqq = (HttpServletRequest)req;
        HttpServletResponse respp = (HttpServletResponse)resp;

        //设置字符集
        reqq.setCharacterEncoding("UTF-8");
        respp.setContentType("text/html;charset=utf-8");

        PrintWriter out = respp.getWriter();
        //获取数据
        String date = reqq.getParameter("date");
        //判断昵称/邮箱是否为空
        if (date.equals("")){
            out.println("<script>alert('请输入昵称/邮箱');location.href='/lyq/shangc/forget.jsp';</script>");
            out.close();
            return;
        }else {
            Pattern pt = Pattern.compile("^\\w+@[0-9a-z]+\\.[a-z]+$");
            Matcher mt = pt.matcher(date);
            Pattern pt1 = Pattern.compile("[a-zA-Z\\u4E00-\\u9FA5]*");
            Matcher mt1 = pt1.matcher(date);
            if (!mt1.matches() && !mt.matches()){
                out.println("<script>alert('昵称/邮箱格式不正确');location.href='/lyq/shangc/forget.jsp';</script>");
                out.close();
                return;
            }
        }

        //验证验证码是否正确
        HttpSession session = reqq.getSession();
        String verycode = reqq.getParameter("verycode");
        String syscode = (String)session.getAttribute("code");
        if (verycode.equals("")){
            out.println("<script>alert('验证码不能为空');location.href='/lyq/shangc/forget.jsp';</script>");
            out.close();
            return;
        }else  if (!syscode.equals(verycode)){
            out.println("<script>alert('验证码输入有误');location.href='/lyq/shangc/forget.jsp';</script>");
            out.close();
            return;
        }

        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
